const express = require('express')
const app = express()

const fs= require('fs')
var https = require('https');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.cert', 'utf8');
var credentials = {key: privateKey, cert: certificate};

// const { nextTick } = require('process');
 const httpsServer = https.createServer( credentials, app);



const server = require('http').Server(app)
const io = require('socket.io')(server)
const iohttps=require('socket.io')(httpsServer)
const { v4: uuidV4 } = require('uuid')

var cors=require('cors')
app.use(cors())
app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/', (req, res) => {
  res.redirect(`/${uuidV4()}`)
})

app.get('/:room', (req, res) => {
  res.render('room', { roomId: req.params.room })
})

// io.on('connection', socket => {

//     var address = socket.handshake.address;
//     console.log('New connection from ' + address.address + ':' + address.port);

//   socket.on('join-room', (roomId, userId) => {
//     socket.join(roomId)
//     socket.to(roomId).broadcast.emit('user-connected', userId)

//     socket.on('disconnect', () => {
//       socket.to(roomId).broadcast.emit('user-disconnected', userId)
//     })
//   })
// })
io.of('/surf').on('connection', socket => {
  var ip = socket.handshake.headers["x-real-ip"];
  var port = socket.handshake.headers["x-real-port"];
  var clientIp = socket.request.connection.remoteAddress;
console.log(clientIp)})
iohttps.on('connection', socket => {
  var ip = socket.handshake.headers["x-real-ip"];
  var port = socket.handshake.headers["x-real-port"];
  var clientIp = socket.request.connection.remoteAddress;
console.log(clientIp)
  socket.on('join-room', (roomId, userId) => {
    socket.join(roomId)
    socket.to(roomId).broadcast.emit('user-connected', userId)
    // socket.on('stream',(u,s)=>{
    //   socket.to(roomId).broadcast.emit('stream',u,s)
    // })
    socket.on('disconnect', () => {
      socket.to(roomId).broadcast.emit('user-disconnected', userId)
    })
  })

})

// server.listen(3000)
httpsServer.listen(3003);


const { PeerServer } = require('peer');

const peerServer = PeerServer({
  port: 3002,
  ssl: {
    key: fs.readFileSync('sslcert/server.key'),
    cert: fs.readFileSync('sslcert/server.cert')
  }
});